<?php

namespace api\controller;

// +----------------------------------------------------------------------
// | 合同模板 服务控制层
// +----------------------------------------------------------------------

use common\controller\VerifyController;
use common\service\ContractTemplateService;
use support\ErrorCode;
use think\Request;

class ContractTemplateController extends VerifyController
{

    protected $contractTemplateService;

    /**
     * ContractTemplateController constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->contractTemplateService = ContractTemplateService::getInstance();
    }

    /**
     * 创建模板
     * @param Request $request
     * @return \think\Response
     * @throws \Throwable
     */
    public function create(Request $request)
    {
        /** @var \think\File $tplFile */
        $tplFile = $request->file("tpl_file");

        if (empty($tplFile)) {
            throw_strack_exception("contract file needed", ErrorCode::NO_CONTRACT_FILE);
        }

        if (!$tplFile->check(['ext' => "pdf"])) {
            throw_strack_exception($tplFile->getError(), ErrorCode::CONTRACT_FILE_EXT_MUST_PDF);
        }

        $param = $request->param();
        $res = $this->contractTemplateService->create($param['data'], $tplFile);
        return json(success_response('', $res));
    }

    /**
     * 更新
     * @param Request $request
     * @return \think\Response|void
     */
    public function update(Request $request)
    {
        throw_strack_exception("did not support update", ErrorCode::NOT_SUPPORT_UPDATE);
    }

    /**
     * 删除
     * @param Request $request
     * @return \think\Response
     * @throws \Throwable
     */
    public function delete(Request $request)
    {
        $param = $request->param();
        $res = $this->contractTemplateService->delete($param['param']);
        return json(success_response('', $res));
    }

    /**
     * 查看模板
     * @param Request $request
     * @return \think\Response
     */
    public function view(Request $request)
    {
        $param = $request->param();
        $res = $this->contractTemplateService->view($param['param']);
        return json(success_response('', $res));
    }

    /**
     * 查看模板的可用keys
     * @param Request $request
     * @return \think\Response
     * @throws \think\Exception
     */
    public function getTemplateKeys(Request $request)
    {
        $param = $request->param();
        $res = $this->contractTemplateService->getTemplateKeys($param['param']);
        return json(success_response("", $res));
    }
}
